<template>
    <div class="user-info-page">
        <el-card class="box-card">
            <template #header>
                <span>个人信息</span>
            </template>
            <el-form
                    :model="userInfo"
                    label-width="80px"
                    :rules="rules"
                    status-icon
                    ref="userInfoFormRef"
            >
                <el-form-item label="id" style="display: none">
                    <el-input v-model="userInfo.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="userInfo.userName"></el-input>
                </el-form-item>
                <el-form-item label="账号" prop="userAccount">
                    <el-input v-model="userInfo.userAccount" disabled></el-input>
                </el-form-item>
                <el-form-item>
                    <el-image style="width: 80px;height: 80px;border-radius: 50%" :src="userInfo.avatarUrl"/>
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload
                            class="upload-demo"
                            action="http://localhost:8080/api/files/upload"
                            :on-success="handleFileSuccess"
                            list-type="picture"
                            :before-upload="beforeAvatarUpload"
                            :limit="1"
                    >
                        <el-button type="primary">上传头像</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="userInfo.phone"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button style="margin-right: 80px;width: 100%" type="primary" @click="updateUserInfo">保存
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import myAxios from "@/axios/axios.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {validationRules} from "@/tools/validation.js";
import {useLoginUserStore} from "@/stores/useLoginUserStore.js";

const router = useRouter();
const userInfoFormRef = ref(null);

const loginUserStore = useLoginUserStore()
const userInfo = loginUserStore.loginUser;

// 处理文件上传成功
const handleFileSuccess = (res) => {
    if (res.data) {
        userInfo.avatarUrl = res.data;
        ElMessage.success('头像上传成功');
    } else {
        ElMessage.error('头像上传失败');
    }
};

// 表单验证规则
const rules = reactive({
    userAccount: [{validator: validationRules.validateUserAccount, trigger: 'blur'}],
    userName: [{validator: validationRules.validateUserName, trigger: 'blur'}],
    email: [{validator: validationRules.validateEmail, trigger: 'blur'}],
    phone: [{validator: validationRules.validatePhone, trigger: 'blur'}]
});

// 头像上传前的校验
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/png') {
        ElMessage.error('图片格式需为 jpg !');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB !');
        return false;
    }
    return true;
};
const emit = defineEmits(['updateUserInfo']);
// 更新用户信息
const updateUserInfo = async () => {
    if (!userInfoFormRef.value) return;
    try {
        await new Promise((resolve, reject) => {
            userInfoFormRef.value.validate((valid) => {
                if (valid) {
                    resolve();
                } else {
                    ElMessage.error('表单验证失败，请检查输入信息');
                    reject();
                }
            });
        });
        console.log(userInfo)
        const res = await myAxios.post('/user/update', userInfo);
        if (res.code === 0 && res.data) {
            ElMessage.success('个人信息更新成功');
            localStorage.setItem("code_user", JSON.stringify(res.data));
            // 这里假设你想触发父组件的 updateUser 事件，需要确保父组件监听该事件
            // 若没有父组件监听，可忽略此代码
            // emit('updateUser');
            await router.back();
        } else {
            ElMessage.error('个人信息更新失败');
        }
    } catch (error) {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('更新用户信息出错:', error);
    }
};

</script>

<style scoped>
.user-info-page {
    max-width: 600px;
    margin: 20px auto;
}

.clearfix {
    width: 100px;
    margin: 10px auto;
    color: #2c82ff;
    font-weight: bold;
    font-size: 20px;
}
</style>